﻿namespace DistrRTgen_Service
{
    using DistrRTgen;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Net.Security;
    using System.Net.Sockets;
    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Tcp;
    using System.ServiceProcess;
    using System.Windows.Forms;

    public class DistrRTgenService : ServiceBase
    {
        private IContainer components = null;
        private Server s;

        public DistrRTgenService()
        {
            Environment.CurrentDirectory = Application.CommonAppDataPath;
            
            this.InitializeComponent();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (this.components != null))
            {
                this.components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.components = new Container();
            base.ServiceName = "DistrRTgen Service";
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                Logger.AddLogLine("Starting up", LoggerLevel.LOG_ALERT);
                Dictionary<string, object> props = new Dictionary<string, object>();
                props["port"] = 36433;
                props["name"] = "tcp";
                props["protectionLevel"] = ProtectionLevel.EncryptAndSign;
                props["secure"] = true;
                TcpChannel ch = new TcpChannel(props, new BinaryClientFormatterSinkProvider(), new BinaryServerFormatterSinkProvider());
                ChannelServices.RegisterChannel(ch, true);
                RemotingConfiguration.RegisterWellKnownServiceType(typeof(Server), "distrrtgen", WellKnownObjectMode.Singleton);
                this.s = (Server) Activator.GetObject(typeof(Server), "tcp://localhost:36433/distrrtgen");
                ChainGenerator CG = s.Instance;
                RemotingConfiguration.RegisterWellKnownServiceType(typeof(Logger), "log", WellKnownObjectMode.Singleton);
                Logger.AddLogLine("Working directory: " + Environment.CurrentDirectory, 0);
                CG.AsyncStart();
            }
            catch (SocketException ex)
            {
                Logger.AddLogLine("Could not bind to socket. Unable to start. Details: " + ex.Message, LoggerLevel.LOG_ALERT);
            }
        }

        protected override void OnStop()
        {
            if ((this.s != null) && (this.s.Instance != null))
            {
                this.s.Instance.Stop();
            }
            if (ChannelServices.RegisteredChannels.Length > 0)
            {
                ChannelServices.UnregisterChannel(ChannelServices.RegisteredChannels[0]);
            }
        }
    }
}

